package com.jeecg.p3.system.poster.web;


import com.jeecg.p3.base.util.*;
import com.jeecg.p3.commonweixin.entity.MyJwWebJwid;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.poster.entity.AdvisorCoupon;
import com.jeecg.p3.system.poster.entity.CustomerCoupon;
import com.jeecg.p3.system.poster.entity.ProductCoupon;
import com.jeecg.p3.system.poster.service.AdvisorCouponService;
import com.jeecg.p3.system.poster.service.CustomerCouponService;
import com.jeecg.p3.system.poster.service.ProductCouponService;
import com.jeecg.p3.system.service.MyJwWebJwidService;
import com.jeecg.p3.system.util.Constants;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @ClassName: AdvisorCouponController
 * @Description: TODO 课程优惠券控制层
 * @author: zhangxiao
 * @date: 2020年11月30日 下午7:29:38
 */
@Controller
@RequestMapping("/system/back/poster/advCoupon")
public class AdvisorCouponController extends BaseController {
    public final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private AdvisorCouponService service;
    @Autowired
    private MyJwWebJwidService myJwWebJwidService;
    @Autowired
    private ProductCouponService couponService;
    @Autowired
    private StudyAdvService studyAdvService;
    @Autowired
    private CustomerCouponService customerCouponService;

    @RequestMapping(value = "/toWxuser", method = { RequestMethod.GET, RequestMethod.POST })
    public void toWxuser(HttpServletRequest request, HttpServletResponse response, String toUrl) throws Exception {
        logger.info("toUrl: " + toUrl);
        String viewName = "base/back/common/wxInfo.html";
        VelocityContext velocityContext = new VelocityContext();
        AjaxJson j = WxUtils.getWxUserDetail(request);
        if(j.isSuccess()) {
            request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            velocityContext.put("url", toUrl);
            ViewVelocity.view(request, response, viewName, velocityContext);
        }

    }

    /**
     * 加载优惠券界面
     * @param request
     * @param response
     * @param couponId 优惠券Id
     */
    @RequestMapping(value="/getCoupon",method = {RequestMethod.GET,RequestMethod.POST})
    public void getCoupon(HttpServletRequest request, HttpServletResponse response, String couponId) {
        try {
            logger.info("----------getCoupon.do----start-----------");
            if(StringUtils.isEmpty(couponId)) {//没有优惠券id直接返回空界面
                return;
            }
            AdvisorCoupon advisorCoupon = service.findById(Long.valueOf(couponId));
            if(advisorCoupon == null) {//未根据优惠券id查询到顾问优惠券直接返回空界面
                return;
            }
            String toUrl = ComCode.systemUrl + "/system/back/poster/advCoupon/getCoupon.do?couponId=" + advisorCoupon.getId();
            WxUserInfo wxUserInfo = getWxUserInfo(request);
            //微信用户信息是否保存在seesion,不存在则去获取保存到session中
            if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
                AjaxJson j = WxUtils.getWxUserDetail(request);
                //查看是否存在微信用户信息，存在则保存到session中，不存在则进行跳转去获取微信用户相关信息
                if(j.isSuccess()) {//如果存在微信用户保存到session
                    wxUserInfo = (WxUserInfo) j.getObj();
                    request.getSession().setAttribute(Constants.wxInfo, j.getObj());
                } else {//跳转到微信认证界面获取用户信息
                    String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                            + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                    response.sendRedirect(url);
                    return;
                }
            }
            /*String code = request.getParameter("code");//如果路径存在code则进行在此跳转，否则分享会有问题
            if(com.jeecg.p3.base.util.StringUtils.isNotEmpty(code)) {
                logger.info("------检测到有code进行再次跳转！！！");
                response.sendRedirect(toUrl);
                return;
            }*/
            VelocityContext velocityContext = new VelocityContext();
            String viewName = "system/back/poster/yhj.html";
            logger.info("getCoupon---if---");
            CustomerCoupon customerCoupon = new CustomerCoupon();
            customerCoupon.setAdvCouponId(couponId);
            customerCoupon.setWxOpenId(wxUserInfo.getOpenid());
            customerCoupon.setProductCouponId(advisorCoupon.getProductCouponId());
            List<CustomerCoupon> customeList = customerCouponService.findByParam(customerCoupon);
            if(customeList != null && customeList.size() > 0) {
                logger.info("该客户---已---领取该优惠券！");
                velocityContext.put("isReceive", true);
                velocityContext.put("cusCoupon", customeList.get(0));

            } else {
                logger.info("该客户---未---领取该优惠券！");
                velocityContext.put("isReceive", false);
            }
            MyJwWebJwid myJwWebJwid = myJwWebJwidService.queryByJwid(Constants.wxid);
            String jsapi_ticket = myJwWebJwid.getJsApiTicket();
            Map<String, String> map = JsSignUtil.sign(jsapi_ticket, toUrl);
            velocityContext.put("openId",wxUserInfo.getOpenid());
            velocityContext.put("advisorCoupon",advisorCoupon);
            velocityContext.put("appId", ComCode.appid);
            velocityContext.put("wx",map);
            velocityContext.put("wxInfo", wxUserInfo);
            ViewVelocity.view(request,response,viewName,velocityContext);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param query 顾问优惠券查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/myList.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void myList(@ModelAttribute AdvisorCoupon query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<AdvisorCoupon> pageQuery = new PageQuery<AdvisorCoupon>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        LoginUser user = getCurrentUser(request);
        Boolean isAdmin = isAdmin(request);
        if(!isAdmin) {
            StudyAdviser adviser = this.studyAdvService.findByUserNumber(user.getUserId());
            query.setStudyAdvId(adviser.getId());
        }
        pageQuery.setQuery(query);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        String viewName = "system/back/poster/advisor_coupon_my.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     *
     * @param query 顾问优惠券查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/list.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void toIndividual(@ModelAttribute AdvisorCoupon query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<AdvisorCoupon> pageQuery = new PageQuery<AdvisorCoupon>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        Boolean isAdmin = isAdmin(request);
        if(isMobile(request)) {
            String viewName = "system/back/poster/h5_advisor_coupon.html";
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            if(!isAdmin) {
                query.setCreateUser(getCurrentUser(request).getId());
            }
            pageQuery.setQuery(query);
            List<ProductCoupon> coupons = this.couponService.findByParam(new ProductCoupon());
            velocityContext.put("coupons", coupons);
            List<StudyAdviser> advisers = studyAdvService.findByParam(new StudyAdviser());
            velocityContext.put("advisers", advisers);
            velocityContext.put("advisorCoupon",query);
            velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
            String viewName = "system/back/poster/advisor_coupon.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    /**
     * 跳转到新增顾问优惠券界面页面
     * @return
     */
    @RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public void toAddDialog(HttpServletRequest request, HttpServletResponse response, ModelMap model)throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        List<ProductCoupon> coupons = this.couponService.findByParam(new ProductCoupon());
        velocityContext.put("coupons", coupons);
        List<StudyAdviser> advisers = studyAdvService.findByParam(new StudyAdviser());
        velocityContext.put("advisers", advisers);
        String viewName = "system/back/poster/advisor_coupon_add.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存信息
     * @return
     */
    @RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doAdd(@ModelAttribute AdvisorCoupon advisorCoupon, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            List<AdvisorCoupon> list = service.findByParam(advisorCoupon);
            if(list.size() > 0) {
                j.setSuccess(false);
                j.setMsg("该顾问已经分配过该课程优惠券！");
                return j;
            }
            advisorCoupon.setCreateDate(DateUtil.dateToString(new Date()));
            advisorCoupon.setCreateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            advisorCoupon.setCreateUser(user.getId());
            advisorCoupon.setStatus("1");
            service.doAdd(advisorCoupon);
            j.setMsg("保存成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }

    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping(value="/toEdit",method = RequestMethod.GET)
    public void toEdit(@RequestParam(required = true, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        AdvisorCoupon advisorCoupon = service.findById(id);
        List<ProductCoupon> coupons = this.couponService.findByParam(new ProductCoupon());
        velocityContext.put("coupons", coupons);
        List<StudyAdviser> advisers = studyAdvService.findByParam(new StudyAdviser());
        velocityContext.put("advisers", advisers);
        velocityContext.put("advisorCoupon", advisorCoupon);
        String viewName = "system/back/poster/coupon_edit.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存修改数据
     * @return
     */
    @RequestMapping(value = "/doEdit",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute AdvisorCoupon advisorCoupon, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            List<AdvisorCoupon> list = service.findByParam(advisorCoupon);
            LoginUser user = getCurrentUser(request);
            if(list.size() > 0) {
                j.setSuccess(false);
                j.setMsg("该顾问已经分配过该课程优惠券！");
                return j;
            }
            advisorCoupon.setUpdateDate(DateUtil.dateToString(new Date()));
            advisorCoupon.setUpdateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            advisorCoupon.setUpdateUser(user.getId());
            this.service.doEdit(advisorCoupon);
            j.setMsg("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("编辑失败");
        }
        return j;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value="/doDelete",method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson doDelete(@RequestParam(required = true, value = "id" ) Long id, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            AdvisorCoupon advisorCoupon = service.findById(id);
            advisorCoupon.setDeleteDate(DateUtil.dateToString(new Date()));
            advisorCoupon.setDeleteTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            advisorCoupon.setDeleteUser(user.getId());
            service.doDelete(advisorCoupon);
            j.setMsg("删除成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("删除失败:"+e.getMessage());
        }
        return j;
    }
}
